import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      // routes: {
      //   "new_route": (context) => const NewRoute(),
      //   "router_test_route": (context) => const RouterTestRoute(),
      //   "tip_route": (context) => TipRoute(
      //       text: ModalRoute.of(context)!.settings.arguments.toString()),
      //   "/": (context) => const MyHomePage(title: 'Flutter Demo Home Page'),
      // },
      initialRoute: "/",
      onGenerateRoute: (RouteSettings settings) {
        //如果访问路由需要登录,但当前未登录,则直接返回登录页路由
        String routeName = routeBeforeHook(settings);
        return MaterialPageRoute(builder: (context) {
          switch (routeName) {
            case "/":
              return const MyHomePage(title: 'Flutter Demo Home Page');
            case "login":
              return const MyHomePage(title: 'Flutter Demo Home Page');
            case "tip_route":
              return const TipRoute(text: "hello world");
            case "router_test_route":
              return const RouterTestRoute();
            case "new_route":
              return const NewRoute();
            case "focus_test_route":
              return FocusTestRoute();
            case "form_test_route":
              return FormTestRoute();
            case "progress_route":
              return ProgressRoute();
            default:
              return const Scaffold(
                body: Center(
                  child: Text("页面不存在"),
                ),
              );
          }
        });
      },
      //home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }

  String routeBeforeHook(RouteSettings settings)  {
    Future<SharedPreferences> instance = SharedPreferences.getInstance();
    String token = "";
    instance.then((prefs) => {
     token = prefs.getString("token") ?? ""
    });
    if (token.isEmpty) {
      // return "login";
    }
    return settings.name??"/";
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
            TextButton(
                onPressed: () {
                  Navigator.pushNamed(context, "new_route");
                  // Navigator.push(
                  //     context,
                  //     MaterialPageRoute(
                  //         builder: (context) => const NewRoute()));
                },
                child: const Text("open new route")
            ),
            TextButton(
                onPressed: () {
                  Navigator.pushNamed(context, "router_test_route");
                  // Navigator.push(
                  //     context,
                  //     MaterialPageRoute(
                  //         builder: (context) => const RouterTestRoute()));
                },
                child: const Text("open new TipTestRoute")
            ),
            TextButton(
                onPressed: () {
                  Navigator.pushNamed(context, "form_test_route");
                },
                child: const Text("open new form_test_route")
            ),
            TextButton(
                onPressed: () {
                  Navigator.pushNamed(context, "focus_test_route");
                },
                child: const Text("open new focus_test_route")
            ),
            TextButton(
                onPressed: () {
                  Navigator.pushNamed(context, "progress_route");
                },
                child: const Text("open new progress_route...")
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class NewRoute extends StatelessWidget {
  const NewRoute({super.key});

  @override
  Widget build(BuildContext context) {
    TextEditingController _unameController  = TextEditingController();
    _unameController.addListener(() {
      var text = _unameController.value.text;
      print("controller====$text ");
    });
    return Scaffold(
      appBar: AppBar(
        title: const Text("New Route"),
      ),
      body:  Center(
        child: Column(
          children: [
            TextField(
              autofocus: true,
              controller: _unameController,
              decoration: const InputDecoration(
                labelText: "用户名",
                hintText: "手机号或邮箱",
                icon: Icon(Icons.person),
              ),
            ),
            TextField(
              autofocus: true,
              decoration: const InputDecoration(
                labelText: "密码",
                hintText: "请输入密码",
                prefixIcon: Icon(Icons.lock),
                enabledBorder: OutlineInputBorder(

                )
              ),
              obscureText: true,
              onChanged: (v) {
                print("密码#onChange: $v");
              },
            ),
            // Expanded(
            //   child:ConstrainedBox(
            //     constraints: BoxConstraints(
            //       maxHeight: 40,
            //     ),
            //     child: TextField(
            //       decoration: InputDecoration(
            //         contentPadding: EdgeInsets.fromLTRB(10, 0, 10, 15),
            //         fillColor: Color(0XFFFFF8F4),
            //         filled: true,
            //         enabledBorder: OutlineInputBorder(
            //           /*边角*/
            //           borderRadius: BorderRadius.all(
            //             Radius.circular(5), //边角为5
            //           ),
            //           borderSide: BorderSide(
            //             color: Colors.white, //边线颜色为白色
            //             width: 1, //边线宽度为2
            //           ),
            //         ),
            //         focusedBorder: OutlineInputBorder(
            //           borderSide: BorderSide(
            //             color: Colors.white, //边框颜色为白色
            //             width: 1, //宽度为5
            //           ),
            //           borderRadius: BorderRadius.all(
            //             Radius.circular(5), //边角为30
            //           ),
            //         ),
            //       ),
            //     ),
            //   ),
            //
            // ),
          ],
        ),
      ),
    );
  }
}

class TipRoute extends StatelessWidget {
  const TipRoute({super.key, required this.text});

  final String text;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("提示"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(18),
        child: Center(
          child: Column(
            children: [
              Text(text),
              ElevatedButton(
                  onPressed: () => Navigator.pop(context, "我是返回值"),
                  child: const Text("返回"))
            ],
          ),
        ),
      ),
    );
  }
}

class RouterTestRoute extends StatelessWidget {
  const RouterTestRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        onPressed: () async {
          var result = await Navigator.pushNamed(context, "tip_route",
              arguments: "路由传参");
          // var result = await Navigator.push(
          //     context,
          //     MaterialPageRoute(
          //         builder: (context) => const TipRoute(text: "我是提示XXX")));
          print("路由返回值: $result");
        },
        child: const Text("打开提示"),
      ),
    );
  }
}

class FocusTestRoute extends StatefulWidget {
  @override
  _FocusTestRouteState createState() => _FocusTestRouteState();
}

class _FocusTestRouteState extends State<FocusTestRoute> {
  FocusNode focusNode1 = FocusNode();
  FocusNode focusNode2 = FocusNode();
  FocusScopeNode? focusScopeNode;

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            TextField(
              autofocus: true,
              focusNode: focusNode1,//关联focusNode1
              decoration: InputDecoration(
                  labelText: "input1"
              ),
            ),
            TextField(
              focusNode: focusNode2,//关联focusNode2
              decoration: InputDecoration(
                  labelText: "input2"
              ),
            ),
            Builder(builder: (ctx) {
              return Column(
                children: <Widget>[
                  ElevatedButton(
                    child: Text("移动焦点"),
                    onPressed: () {
                      //将焦点从第一个TextField移到第二个TextField
                      // 这是一种写法 FocusScope.of(context).requestFocus(focusNode2);
                      // 这是第二种写法
                      focusScopeNode ??= FocusScope.of(context);
                      focusScopeNode!.requestFocus(focusNode2);
                    },
                  ),
                  ElevatedButton(
                    child: Text("隐藏键盘"),
                    onPressed: () {
                      // 当所有编辑框都失去焦点时键盘就会收起
                      focusNode1.unfocus();
                      focusNode2.unfocus();
                    },
                  ),
                ],
              );
            },
            ),
          ],
        ),
      ),
    );
  }

}


class FormTestRoute extends StatefulWidget {
  @override
  _FormTestRouteState createState() => _FormTestRouteState();
}

class _FormTestRouteState extends State<FormTestRoute> {
  TextEditingController _unameController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();
  GlobalKey _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("表单"),
      ),
      body: Form(
        key: _formKey, //设置globalKey，用于后面获取FormState
        autovalidateMode: AutovalidateMode.onUserInteraction,
        child: Column(
          children: <Widget>[
            TextFormField(
              autofocus: true,
              controller: _unameController,
              decoration: InputDecoration(
                labelText: "用户名",
                hintText: "用户名或邮箱",
                icon: Icon(Icons.person),
              ),
              // 校验用户名
              validator: (v) {
                return v!.trim().isNotEmpty ? null : "用户名不能为空";
              },
            ),
            TextFormField(
              controller: _pwdController,
              decoration: InputDecoration(
                labelText: "密码",
                hintText: "您的登录密码",
                icon: Icon(Icons.lock),
              ),
              obscureText: true,
              //校验密码
              validator: (v) {
                return v!.trim().length > 5 ? null : "密码不能少于6位";
              },
            ),
            // 登录按钮
            Padding(
              padding: const EdgeInsets.only(top: 28.0),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: ElevatedButton(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Text("登录"),
                      ),
                      onPressed: () {
                        // 通过_formKey.currentState 获取FormState后，
                        // 调用validate()方法校验用户名密码是否合法，校验
                        // 通过后再提交数据。
                        if ((_formKey.currentState as FormState).validate()) {
                          //验证通过提交数据
                        }
                      },
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

class ProgressRoute extends StatefulWidget {
  @override
  _ProgressRouteState createState() => _ProgressRouteState();
}

class _ProgressRouteState extends State<ProgressRoute>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;

  @override
  void initState() {
    //动画执行时间3秒
    _animationController = AnimationController(
      vsync: this, //注意State类需要混入SingleTickerProviderStateMixin（提供动画帧计时/触发器）
      duration: Duration(seconds: 3),
    );
    _animationController.forward();
    _animationController.addListener(() => setState(() => {}));
    super.initState();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
          children: <Widget>[
      Padding(
      padding: EdgeInsets.all(16),
      child: LinearProgressIndicator(
        backgroundColor: Colors.grey[200],
        valueColor: ColorTween(begin: Colors.grey, end: Colors.blue)
            .animate(_animationController), // 从灰色变成蓝色
        value: _animationController.value,
      ),
    ),
    ],
    ),
    );
  }
}